package com.iamteer.day20;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 完成图片 Copy
 */
public class CopyJPG {

	public static void main(String[] args) throws IOException {
		// copyJPG1();
		copyJGP2();
	}

	/*
	 * private static void copyJPG1() throws IOException { //1. 找到目标文件 File
	 * inFile = new File("from.jpg"); File outFile = new File("to.jpg");
	 * 
	 * //2. 建立数据通道 FileInputStream fileInputStream = new
	 * FileInputStream(inFile); FileOutputStream fileOutputStream = new
	 * FileOutputStream(outFile); //这里不需要true，因为没有关闭
	 * 
	 * //3. 读取、处理、写出数据 byte[] buf = new byte[1024]; int length = -1; while
	 * ((length = fileInputStream.read(buf)) != -1) {
	 * System.out.println(Arrays.toString(buf)); fileOutputStream.write(buf, 0,
	 * length); } //4. 关闭文件资源：先开后关 fileOutputStream.close();
	 * fileInputStream.close(); }
	 */

	public static void copyJGP2() {
		FileInputStream fileInputStream = null;
		FileOutputStream fileOutputStream = null;

		try {
			// 1. 找到目标文件
			File inFile = new File("from1.jpg");
			File outFile = new File("to.jpg");
			// 2. 建立数据通道
			fileInputStream = new FileInputStream(inFile);
			fileOutputStream = new FileOutputStream(outFile);
			// 3. 建立缓冲数组，进行读取操作
			byte[] buf = new byte[1024];
			int length = -1;
			while ((length = fileInputStream.read(buf)) != -1) {
				fileOutputStream.write(buf, 0, length);
			}
			System.out.println("拷贝成功。。。");
		} catch (IOException e) {
			System.out.println("拷贝失败。。。");
			throw new RuntimeException(e);
		} finally { // 关闭文件资源
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
					System.out.println("关闭输出流成功！");
				} catch (IOException e) {
					System.out.println("\n关闭输出流失败！");
					throw new RuntimeException(e);
				} finally {

					if (fileInputStream != null) {
						try {
							fileInputStream.close();
							System.out.println("关闭输入流成功！");
						} catch (IOException e) {
							System.out.println("\n关闭输入流失败！");
							throw new RuntimeException(e);
						}
					}
				}
			}
		}
	}
}
